import {
    RouteRecordRaw,
    createRouter,
    createWebHistory,
} from "vue-router";
import pages from './index-page'
import { useAppStoreWithOut } from "@/store/modules/app";

const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
        meta: {
            title: "登录"
        }
    },
    {
        path: "/",
        name: 'Layout',
        component: () => import('@/layout/index.vue'),
        redirect: "/home",
        meta: {
            title: "首页"
        },
        children: pages
    },
    {
        path: "/:pathMatch(.*)*",
        name: '404',
        component: () => import('@/views/404/index.vue'),
        meta: {
            title: "404"
        }
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
});
const appStore = useAppStoreWithOut()
// 路由守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    document.title = to.meta?.title as string || '后台管理系统'
    const token = appStore.getToken
     if (to.path !== '/login' && !token) {
        next('/login')
     }else{
        next()
     }
    // // 检查是否需要登录
    // const token = localStorage.getItem('token')
    // if (to.path !== '/login' && !token) {
    //     next('/login')
    // } else {
    //     // 检查权限
    //     const roles = to.meta?.roles as string[] | undefined
    //     if (roles && roles.length > 0) {
    //         const userRole = localStorage.getItem('userRole')
    //         if (!userRole || !roles.includes(userRole)) {
    //             next('/404')
    //             return
    //         }
    //     }
    //     next()
    // }
})

export default router;
